let app = getApp();
import {  getSupplierData, getGoodsAreas,getGoodsList,getGoodsSetmeal,getOrderLeaseTerm} from "../../../api/index";

import {  makeLineOrder } from "../../../api/order";

import { uploadImg } from "../../../utils/request";
import { disposeData } from "../../../utils/outData";
import {
  checkName,
  checkPhone,
  validateIdCard,
  checkRegisterCode,
} from "../../../utils/validate";
Page({
  data: {
    people: '',
    contact_tel: '',
    shopname: '',
    shoptype: '',
    photo: '',
    faptype: '',
    mechanism: '',
    companyid: '',
    shopcity: '',
    company_area: '',
    area_id: '',
    company: '',
    shopcard: '',
    doorphoto: '',
    spec_id: '',
    faname: '',
    idcard: '',
    faidcard: '',
    faidcard_back: '',
    showFaptype: false,
    popupData: {},
    fapList: [],
    phone_index: -1,
    setmeal_index:-1,
    areasList: [],
    relationId: '', // 分销产品供应商入驻关联id
    tabs: [
      { id: 0, title: '新机' },
      { id: 1, title: '旧机' }
    ],
    isAgree:0,
    salePricea:'',
    etc:1,
    productList:[],
    guidePrice:0,
    salePrice:'',
    goodsImg:'',
    leaseInfo:'',
    seller_id:'',
    shopname:'',
  },
  onLoad(options) {
    this.setData({
      shopname: options.shopname || disposeData().shopname,
      seller_id: options.member_id || disposeData().memberId
    })
    this.getProductList()
    // this.getCitys()
  },
  onScan() {
    my.scan({
      success: (res) => {
        console.log('扫码成功', res);
        my.ap.openURL({
          url: res.qrCode, // 请将 url 替换为有效的页面地址
          success: (res) => {
            console.log('openURL success', res)
          },
          fail: (err) => {
            console.log('openURL success', err)
          }
        });
        
        // 处理扫码结果，例如显示给用户或发起支付
      },
      fail: (error) => {
        console.error('扫码失败', error);
      }
    });
  },
  changeAgree(e) {
    const { id } = e.currentTarget.dataset
    this.setData({ isAgree:id})
    if (!this.data.salePricea) {
      this.showMsg('售价不能为空')
      return;
    }
    let leaseInfo = []

    let salePrice=this.data.salePricea;
    if(id=='1'){
      salePrice=parseFloat(salePrice *1.1).toFixed(2);
    }else  if(id=='2'){
      salePrice=parseFloat(salePrice *1.2).toFixed(2);
    }else  if(id=='3'){
      salePrice=parseFloat(salePrice *1.25).toFixed(2);
    }else  if(id=='4'){
      salePrice=parseFloat(salePrice *1.30).toFixed(2);
    }else  if(id=='5'){
      salePrice=parseFloat(salePrice *1.15).toFixed(2);
    }
    let firstRent=parseFloat(this.data.salePricea * id*0.1).toFixed(2);
    let idindex='';
    let eRent='';

    if(id=='4'){
      idindex=8;
      eRent=parseFloat((salePrice-firstRent)/8).toFixed(2);
    }else{
     idindex=5;
     eRent=parseFloat((salePrice-firstRent)/5).toFixed(2);
    }
    console.log(firstRent);
    firstRent=Number(firstRent)+100;
    salePrice=Number(salePrice)+100;
    this.setData({salePrice: salePrice,firstRent:firstRent });

    var temp = new Date(new Date());
    temp.setMonth(temp.getMonth());

    var tempa = new Date(new Date());
    tempa.setMonth(tempa.getMonth() + 1);//由于设计缺陷，要在设置月份的时候就加1
    let montha=temp.getFullYear()+'.'+parseFloat(temp.getMonth()+1)+'.'+temp.getDate()+'-'+tempa.getFullYear()+'.'+parseFloat(tempa.getMonth()+1)+'.'+tempa.getDate();

    let anotherObject=[];
    anotherObject = {
      lease_term: montha,
      lease_price: firstRent,
      which_period: '第1期'
    };
    leaseInfo.push(anotherObject);
    for (let index = 0; index < idindex; index++) {
      var temp = new Date(new Date());
      // 原来是2018年8月7日，加6个月后应该是2019年2月7日
      temp.setMonth(temp.getMonth() + index+1);//由于设计缺陷，要在设置月份的时候就加1

      var tempa = new Date(new Date());
      tempa.setMonth(tempa.getMonth()+1+index+1);//由于设计缺陷，要在设置月份的时候就加1

      let month=temp.getFullYear()+'.'+parseFloat(temp.getMonth()+1)+'.'+temp.getDate()+'-'+tempa.getFullYear()+'.'+parseFloat(tempa.getMonth()+1)+'.'+tempa.getDate();
      anotherObject = {
        lease_term: month,
        lease_price: eRent,
        which_period: '第'+parseFloat(index+2).toFixed(0)+'期'
      };
      leaseInfo.push(anotherObject);
    }
  //  console.log(leaseInfo);
   this.setData({
    leaseInfo: leaseInfo
    })
  },
  openStagesModal(){
    this.setData({
      stagesModal: true
    })
  },
  closestagesModal(){
    this.setData({
      stagesModal: false
    })
  },
  changeConfirm(e) {
    const { id } = e.currentTarget.dataset
    this.setData({ etc:id})
    this.getProductList()
  },
  getPopupDats() {
    getSupplierData().then(res => {
      let arr1 = Object.keys(res.fap_type).map((key, index) => ({ name: res.fap_type[key], id: index + 1 }))
      let arr2 = Object.keys(res.risk_type).map(key => ({ name: res.risk_type[key] }))
      // arr1.map((item, index) => {
      //   item["checked"] = false;
      // });
      // arr2.map((item, index) => {
      //   item["checked"] = false;
      // });
      this.setData({
        popupData: res,
        fapList: arr1
      })
    })
  },
  handleTabClick({ index, tabsName }) {
    this.setData({
      [tabsName]: index,
    });
  },
  selectPhone(e) {
    console.log(e);
    this.setData({
      phone_index: e.detail.value,
      phoneGoods: this.data.productList[e.detail.value].id.toString()
    });
    getGoodsSetmeal(this.data.phoneGoods).then(res => {
      let newArr = []
      for (let key in res) {
        newArr.push(res[key])
      }

      newArr.forEach(item => {
        if (item.title) {
          item['name'] = item.title
        }
      })
      this.setData({
        setmeailList: newArr || []
      });
     console.log(this.data.setmeailList);
 
    })
  },
  selectSetmeal(e) {
    console.log(e);
    this.setData({
      setmeal_index: e.detail.value,
      phoneSetmeal: this.data.setmeailList[e.detail.value].id.toString(),
      guidePrice: this.data.setmeailList[e.detail.value].spec[0].total_amount.toString(),
      spec_id: this.data.setmeailList[e.detail.value].spec[0].id.toString()
    });
  },
    // 获取分类列表
    getProductList() {
      getGoodsList({
        cate_id: this.data.etc==2?'24':'3',
        orderby_name:'id',
        sort:'desc',
      }).then(res => {
        let newArr = []
        for (let key in res.data) {
          newArr.push(res.data[key])
        }
 
        newArr.forEach(item => {
          if (item.title) {
            item['name'] = item.title
          }
        })
        this.setData({
          productList: newArr || []
        });
      }).catch(err =>{
      })
    },

  onPeople(e) {
    this.setData({ salePrice: e.detail.value })
  },
  onZhima(e) {
    this.setData({ zhimaScore: e.detail.value })
  },
  onHuabei(e) {
    this.setData({ huabeiAmount: e.detail.value })
  },
  onFaname(e) {
    this.setData({ faname: e.detail.value })
  },
  onIdcard(e) {
    this.setData({ idcard: e.detail.value })
  },
  onJob(e) {
    this.setData({ contact_mobile: e.detail.value })
  },
  onPhone(e) {
    this.setData({ phone: e.detail.value })
  }, 
  onCompany(e) {
    this.setData({ contact_name: e.detail.value })
  },
  onSalePrice(e) {
    this.setData({ salePricea: e.detail.value })
    if(!this.data.guidePrice){
      this.showMsg('请先选择型号和配置')
      return;
    }
    console.log(this.data.guidePrice);
    console.log(e.detail.value);

    if(Number(this.data.guidePrice)<Number(e.detail.value)){
      this.showMsg('售价不能高于指导价')
      return;
    }
  },

 
  onReset_faptype(e) {
    this.setData({ showFaptype: false });
  },
  getCitys() {
    getGoodsAreas().then(res => {
      this.setData({
        areasList: res[0].sub
      })
    })
  },
  getList(type) {
    const { areasList } = this.data;
    let list = [];
    for (let p of areasList) {
      if (type == '1' && p.id == 7459) {
        continue;
      }
      let obj = {
        name: p.name,
        subList: []
      }
      if (p.sub) {
        for (let c of p.sub) {
          let obj1 = {
            name: c.name,
            subList: []
          }
          if (c.sub) {
            for (let ct of c.sub) {
              obj1.subList.push({
                name: ct.name,
              })
            }
          }
          obj.subList.push(obj1);
        }
      }
      list.push(obj);
    }
    return list;
  },
  selectShopcity(e) {
    const type = e.target.dataset.type;
    const list = this.getList(type);
    let selectTitle = type == '1' ? '公司所在地区' : '当前经营位置'
    my.multiLevelSelect({
      title: selectTitle,//级联选择标题
      list: list,
      success: (res) => {
        if (res.success) {
          let area = "", area_id = "";
          res.result.forEach((element, index) => {
            if (index > 0) {
              area += '-' + element.name;
            } else {
              area += element.name;
            }
          });
          for (let p of this.data.areasList) {
            if (p.name == res.result[0].name) {
              for (let c of p.sub) {
                if (c.name == res.result[1].name) {
                  area_id = c.id;
                }
              }
            }
          }
          if (type == 1) {
            this.setData({
              company_area: area,
              area_id
            })
          } else {
            this.setData({
              shopcity: area
            })
          }
        }
      }
    });
  },
  onPopupClose() {
    this.setData({
      showFaptype: false
    });
  },

  uploadPhoto(e) {
    const that = this;
    let type = e.currentTarget.dataset.type
    switch (type) {
      case "photo":
        uploadImg(function (url) {
          if (url) {
            that.setData({ photo: url })
          }
        });
        break;
      case "shopcard":
        uploadImg(function (url) {
          if (url) {
            that.setData({ shopcard: url })
          }
        });
        break;
      case "doorphoto":
        uploadImg(function (url) {
          if (url) {
            that.setData({ doorphoto: url })
          }
        });
        break;
      case "seal_url":
        uploadImg(function (url) {
          if (url) {
            that.setData({ seal_url: url })
          }
        });
        break;
      case "faidcard":
        uploadImg(function (url) {
          if (url) {
            that.setData({ faidcard: url })
          }
        });
        break;
      case "faidcard_back":
        uploadImg(function (url) {
          if (url) {
            that.setData({ faidcard_back: url })
          }
        });
        break;

      default:
        break;
    }
  },
  showMsg(msg) {
    my.showToast({
      type: 'none',
      duration: 1000,
      content: msg
    });
  },
  submitBtn() {
    const that = this
    const { faname, contact_tel, shopname, etc, phoneGoods , phoneSetmeal , companyid, salePrice, 
      zhimaScore, huabeiAmount, company, phone, contact_name, job, contact_mobile,idcard, faidcard, faidcard_back, isAgree } = that.data
 
    if (!phoneGoods) {
      this.showMsg('请选择型号')
      return;
    }
    if (!phoneSetmeal) {
      this.showMsg('请选择配置')
      return;
    }
    if (!salePrice) {
      this.showMsg('售价不能为空')
      return;
    }
   

    if (!zhimaScore) {
      this.showMsg('芝麻信用分不能为空')
      return;
    }
    if (!huabeiAmount) {
      this.showMsg('下单人花呗总额度不能为空')
      return;
    }
    if (!isAgree) {
      this.showMsg('请选择购机方式')
      return;
    }
    if (!checkName(faname)) {
      return;
    }
    if (!validateIdCard(idcard)) {
      return;
    }
    if (!checkPhone(phone)) {
      return;
    }
    
    if (!contact_name) {
      this.showMsg('紧急联系人姓名不能为空')
      return;
    }

    if (!contact_mobile) {
      this.showMsg('紧急联系人电话不能为空')
      return;
    }

   
    // if (!faidcard||!faidcard_back) {
    //   this.showMsg('请上传身份证')
    //   return;
    // }
    let obj =this.data;
   
    makeLineOrder(obj).then(res => {
      this.showMsg('提交成功')
      my.navigateTo({
        url: '../../../pages/authentication/authentication?orderId=' + res.order_id + '&goodsId=' + that.data.phoneGoods + '&payType=1'  +  '&setmealId=' + that.data.phoneSetmeal
        + '&specId=' + that.data.spec_id + '&amount=' + that.data.salePrice + '&name'+that.data.faname+'&mobile'+that.data.phone+'&contractType=1'+ '&type=1'+'&seller_id'+that.data.seller_id
      })
    })
  }
});
